import random
import kohutils

class Deck:

    def __init__(self):
        self.cards = []
        self.generateDeck()

    def generateDeck(self, decks=1):
        for iii in range(decks):
            for i in range(4):
                for ii in range(9):
                    self.cards.append( (self.card_suit(i), str(2+ii)) )
                self.cards.append( (self.card_suit(i), 'J') )
                self.cards.append( (self.card_suit(i), 'Q') )
                self.cards.append( (self.card_suit(i), 'K') )
                self.cards.append( (self.card_suit(i), 'A') )

    def card_suit(self, suit):
        if suit == 0:
            return 'S'
        elif suit == 1:
            return 'H'
        elif suit == 2:
            return 'C'
        elif suit == 3:
            return 'D'
        else:
            raise ValueError
            
    def shuffle(self):
        random.shuffle(self.cards)
        
    def deal_to(self, _list, _amount):
        for i in range(_amount):
            _list.append(self.cards.pop(0))
            
    def length(self):
        return len(self.cards)

    def discard(self):
        self.cards = []
                 
class Field:
    def __init__(self):
        self.played = [] # the played pile
        self.last_card_played = ("None") # last card that was played
        self.played_value = 0 # value of the last played card
        self.discarded = [] # discarded cards NOT removed from play
        self.dead = [] # discarded cards removed from play (3,7,10)

    def add_played(self, cards_played):
        if not cards_played:
            return false

        for card in cards_played:
            self.played.append(card)

        self.last_card_played = self.played[len(self.played) - 1]
        self.played_value = self.last_card_played[1]
        return True

    def discard_field(self):
        self.add_discarded(self.played)
        self.played = []

    def add_discarded(self, cards_discarded):
        if not cards_discarded:
            return False

        for card in cards_discarded:
            self.discarded.append(card)
            
        self.sort_discarded()
        return True

    def top_card(self):
        return self.last_card_played

    def get_discarded(self):
        return self.discarded

    def sort_discarded(self):
        self.discarded = kohutils.sort_cards(self.discarded)

    def show_discarded(self):
        if self.discarded:
            for card in self.discarded:
                print(''.join(card), end = '\t')

            print('\n')
        else:
            print("No cards have been discarded yet\n")
    
    def get_dead(self):
        return self.dead
